package docBuilder;

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class NewMain {

    public static void main(String[] args) {
        try{
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(new File("cd_catalog.xml"));
        NodeList titleNodes = doc.getElementsByTagName("title");
        System.out.println("Count :" + titleNodes.getLength());

            //Upper title len chu Hoa
            for (int i = 0; i < titleNodes.getLength(); i++) {
                String title = titleNodes.item(i).getTextContent();
                titleNodes.item(i).setTextContent(title.toUpperCase());
            }

        //Tao doi tuong node moi la Item
        Node newItem = doc.createElement("cd");
        Node newTitle = doc.createElement("title");
        Node newArtist = doc.createElement("artist");
        Node newCountry = doc.createElement("country");
        Node newCompany = doc.createElement("company");
        Node newPrice = doc.createElement("price");
        Node newYear = doc.createElement("year");

        newTitle.setTextContent("Romantic9x");
        newArtist.setTextContent("Thaodd");
        newCountry.setTextContent("Viet Nam");
        newCompany.setTextContent("Fpt-Apt");
        newPrice.setTextContent("2.8 $");
        newYear.setTextContent("2009");

        newItem.appendChild(newTitle);
        newItem.appendChild(newArtist);
        newItem.appendChild(newCountry);
        newItem.appendChild(newCompany);
        newItem.appendChild(newPrice);
        newItem.appendChild(newYear);

        doc.getDocumentElement().appendChild(newItem);
        Source source = new DOMSource(doc);

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        Result result = new StreamResult(new File("other_catalog.xml"));

        transformer.transform(source, result);
        System.out.println("OK");

        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
